package com.puhui.lib.utils;

import android.content.Context;
import android.view.inputmethod.InputMethodManager;

import java.lang.reflect.Field;

/**
 * 内存泄漏相关的工具类
 */
public class MemoryLeakUtils {

    /**
     * 释放由于InputMethodManager引起的内存泄漏
     */
    public static void fixInputMethodManagerLeak(Context context) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        try {
            /**
             * 将这个字段sInstance置空后出现以下异常。操作：回到桌面在点击图标就崩溃了
             * java.lang.IllegalArgumentException: unknown client android.os.BinderProxy@5a6e084
             *   at com.android.internal.view.IInputMethodManager$Stub$Proxy.startInputOrWindowGainedFocus(IInputMethodManager.java:738)
             *   at android.view.inputmethod.InputMethodManager.onPostWindowFocus(InputMethodManager.java:1627)
             */
//            Field sInstance = InputMethodManager.class.getDeclaredField("sInstance");

            Field mLastSrvView = InputMethodManager.class.getDeclaredField("mLastSrvView");
            Field mServedView = InputMethodManager.class.getDeclaredField("mServedView");
            Field mNextServedView = InputMethodManager.class.getDeclaredField("mNextServedView");

            //InputMethodManager里面没有这个字段mLastSrvView   但是分析却说这个字段也保持了引用
            //部分华为手机修改了rom，新增了这个字段

            mLastSrvView.setAccessible(true);
            mLastSrvView.set(inputMethodManager, null);
            mServedView.setAccessible(true);
            mNextServedView.setAccessible(true);
            mServedView.set(inputMethodManager, null);
            mNextServedView.set(inputMethodManager, null);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
